package net.tv90.shoppingserver.dao;

import net.tv90.shoppingserver.model.domain.Good;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;

@Repository
public interface GoodRepository extends JpaRepository<Good, Integer> {

    @Query("SELECT g FROM Good g " +
            "WHERE (:name IS NULL OR g.name LIKE CONCAT('%', :name, '%')) " +
            "AND (:priceStart IS NULL OR g.price >= :priceStart) " +
            "AND (:priceEnd IS NULL OR g.price <= :priceEnd) " +
            "AND (:stockStart IS NULL OR g.stock >= :stockStart) " +
            "AND (:stockEnd IS NULL OR g.stock <= :stockEnd)")
    Page<Good> findGoodsByConditions(String name, BigDecimal priceStart, BigDecimal priceEnd,
                                     Integer stockStart, Integer stockEnd, PageRequest pageRequest, Sort sort);

    @Query("SELECT count(*) FROM Good g " +
            "WHERE (:name IS NULL OR g.name LIKE CONCAT('%', :name, '%')) " +
            "AND (:priceStart IS NULL OR g.price >= :priceStart) " +
            "AND (:priceEnd IS NULL OR g.price <= :priceEnd) " +
            "AND (:stockStart IS NULL OR g.stock >= :stockStart) " +
            "AND (:stockEnd IS NULL OR g.stock <= :stockEnd)")
    Integer countGoodsByConditions(String name, BigDecimal priceStart, BigDecimal priceEnd,
                                   Integer stockStart, Integer stockEnd);
}
